package com.example.lvsuo.Execl.Execldaoru;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;


@RestController
public class TaskController {
    // 改  调用 需要使用的service-----------------
    @Autowired
    TaskService ts;
    @PostMapping("/import")
    public String analysisExcel(MultipartFile file) throws IOException {

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();

            Workbook workbook = null;
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".xls".equals(fileType)) {
                workbook = new HSSFWorkbook(inputStream);
            } else if (".xlsx".equals(fileType)) {
                workbook = new XSSFWorkbook(inputStream);
            }

            ArrayList<ArrayList<Object>> list = new ArrayList<>();

            Sheet sheet;  Row row;  Cell cell;
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                sheet = workbook.getSheetAt(i);
                for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                    row = sheet.getRow(j);
                    if (row != null && row.getFirstCellNum() != j) {
                        ArrayList tempList = new ArrayList();
                        for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                            cell = row.getCell(k);
                            tempList.add(cell.getStringCellValue());
                        }
                        list.add(tempList);
                    }
                }
            }
            //改 调用service的方法-----------------参数必须写list
            ts.lists(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            inputStream.close();
        }
        return "success";
    }
}


